<template>
  <PageContainer>
    <template #header>
      <div class="detail-header">
        <el-button 
          :icon="ArrowLeft" 
          @click="handleBack"
          class="back-button"
        >
          返回列表
        </el-button>
        <span class="detail-title">{{ discussion.title || '讨论详情' }}</span>
      </div>
    </template>

    <div class="discussion-detail" v-loading="loading">
      <!-- 讨论内容区域 -->
      <el-card class="discussion-content">
        <template #header>
          <div class="discussion-header">
            <div class="author-info">
              <el-avatar 
                :src="discussion.author?.avatar" 
                :size="50"
                class="author-avatar"
              >
                {{ discussion.author?.nickname?.charAt(0) || discussion.author?.username?.charAt(0) || '?' }}
              </el-avatar>
              <div class="author-details">
                <div class="author-name">{{ discussion.author?.nickname || discussion.author?.username || '未知用户' }}</div>
                <div class="discussion-meta">
                  <span class="discussion-time">{{ formatTime(discussion.pub_date) }}</span>
                  <el-tag 
                    v-if="discussion.category" 
                    :type="discussion.category === '写作技巧' ? 'success' : 
                           discussion.category === '作品讨论' ? 'warning' : 
                           discussion.category === '行业动态' ? 'danger' : 'info'"
                    size="small"
                  >
                    {{ discussion.category }}
                  </el-tag>
                </div>
              </div>
            </div>
            <div class="discussion-stats">
              <el-button type="primary" @click="handleLike">
                <el-icon><Star /></el-icon>
                点赞 ({{ discussion.likes || 0 }})
              </el-button>
            </div>
          </div>
        </template>

        <div class="discussion-body">
          <div class="discussion-text">{{ discussion.content }}</div>
          
          <!-- 标签 -->
          <div v-if="discussion.tags && discussion.tags.length > 0" class="discussion-tags">
            <el-tag
              v-for="tag in discussion.tags"
              :key="tag"
              size="small"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <template #footer>
          <div class="discussion-footer-stats">
            <span><el-icon><View /></el-icon> 浏览 {{ discussion.views || 0 }}</span>
            <span><el-icon><ChatDotRound /></el-icon> 评论 {{ discussion.comment_count || 0 }}</span>
            <span><el-icon><Star /></el-icon> 点赞 {{ discussion.likes || 0 }}</span>
            <span>最后更新: {{ formatTime(discussion.last_modified) }}</span>
          </div>
        </template>
      </el-card>

      <!-- 评论区域 -->
      <div id="comments-section" class="comments-section">
        <CommentSection 
          :discussion-id="discussionId"
          :discussion-title="discussion.title"
          @comment-added="handleCommentAdded"
          @comment-deleted="handleCommentDeleted"
        />
      </div>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { View, Star, ArrowLeft, ChatDotRound } from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import CommentSection from '@/views/article/components/CommentSection.vue'
import { getDiscussionDetail, likeDiscussion } from '@/api/discuss'

const route = useRoute()
const router = useRouter()
const discussionId = route.params.id

// 讨论详情数据
const discussion = ref({})
const loading = ref(false)

// 获取讨论详情
const fetchDiscussionDetail = async () => {
  loading.value = true
  try {
    const response = await getDiscussionDetail({ id: discussionId })
    if (response.data.code === '0000') {
      discussion.value = response.data.data
      
      // 如果有锚点，滚动到评论区域
      nextTick(() => {
        if (route.hash === '#comments') {
          const commentsSection = document.getElementById('comments-section')
          if (commentsSection) {
            commentsSection.scrollIntoView({ behavior: 'smooth' })
          }
        }
      })
    } else {
      ElMessage.error(response.data.msg || '获取讨论详情失败')
    }
  } catch (error) {
    console.error('获取讨论详情失败:', error)
    ElMessage.error('获取讨论详情失败')
  } finally {
    loading.value = false
  }
}

// 点赞讨论
const handleLike = async () => {
  try {
    const response = await likeDiscussion({ discussionId: discussionId })
    if (response.data.code === '0000') {
      discussion.value.likes = response.data.data.likes
      ElMessage.success('点赞成功')
    } else {
      ElMessage.error(response.data.msg || '点赞失败')
    }
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败')
  }
}

// 返回讨论列表
const handleBack = () => {
  router.push('/article/forum')
}

// 评论添加后的回调
const handleCommentAdded = () => {
  // 更新评论计数
  discussion.value.comment_count += 1
  ElMessage.success('评论发布成功')
}

// 评论删除后的回调
const handleCommentDeleted = () => {
  // 更新评论计数
  if (discussion.value.comment_count > 0) {
    discussion.value.comment_count -= 1
  }
  ElMessage.success('评论删除成功')
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '未知时间'
  
  const date = new Date(timeString)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 初始化
onMounted(() => {
  fetchDiscussionDetail()
})
</script>

<style scoped>
.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  margin-right: 16px;
}

.detail-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.discussion-detail {
  padding: 20px;
}

.discussion-content {
  margin-bottom: 30px;
}

.discussion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-avatar {
  flex-shrink: 0;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.discussion-meta {
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.discussion-time {
  color: #999;
  font-size: 14px;
}

.discussion-stats {
  display: flex;
  gap: 8px;
}

.discussion-body {
  padding: 16px 0;
}

.discussion-text {
  line-height: 1.8;
  color: #333;
  font-size: 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.discussion-tags {
  margin-top: 16px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 4px;
}

.discussion-footer-stats {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
  align-items: center;
}

.discussion-footer-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.comments-section {
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .discussion-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .discussion-stats {
    align-self: flex-end;
  }
  
  .discussion-footer-stats {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .back-button {
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .discussion-detail {
    padding: 10px;
  }
}
</style>